package top.carrotguo.weibo.ui.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;
import com.orhanobut.logger.Logger;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import butterknife.ButterKnife;
import top.carrotguo.weibo.bean.HomeTimeLine;
import top.carrotguo.weibo.bean.UserInfo;
import top.carrotguo.weibo.utils.StatusBarUtil;
import top.carrotguo.weibo.view.IView;
import top.carrotguo.weibo.MyApplication;
import top.carrotguo.weibo.R;
import top.carrotguo.weibo.utils.MyConstans;
import top.carrotguo.weibo.utils.ToastUtils;
import top.carrotguo.weibo.widget.LoadingDialog;

public abstract class BaseActivity extends AppCompatActivity implements IView {

    protected MyApplication mApplication;
    protected SharedPreferences sharedPreferences;
    public final String TAG = this.getClass().getSimpleName();
    public UserInfo user;

    protected BaseActivity mContext;
    protected Toolbar mToolbar;
    private LoadingDialog mLoadingDialog;
    public ImmersionBar immersionBar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //初始化状态栏样式
        initStateBar();

        //设置布局
        if (provideContentViewId()!=0) {
            setContentView(provideContentViewId());
            ButterKnife.bind(this);
        } else {
            Logger.e("缺少布局文件");
        }

        //设置上下文
        mContext = this;

        //将bundle传递给子类
        Bundle extras = getIntent().getExtras();
        if (null != extras) {
            getBundleExtras(extras);
        }

        //初始化标题栏
        initToolbar();

        //获取application
        mApplication = (MyApplication) getApplication();
        //获取sharedpreferences
        sharedPreferences = getSharedPreferences(MyConstans.SP_NAME,MODE_PRIVATE);
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }

    /**
     * 初始化白色状态栏
     */
    private void initStateBar(){
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //显示状态栏
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//            StatusBarUtil.setStatusBarColor(BaseActivity.this,R.color.white);
//            说明：
//            1. SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN：Activity全屏显示，但状态栏不会被隐藏覆盖。
//            2. SYSTEM_UI_FLAG_LIGHT_STATUS_BAR：设置状态栏图标为黑色或者白色
//            3. StatusBarUtil 工具类是修改状态栏的颜色为白色。
        //}
        immersionBar = ImmersionBar.with(this);

        immersionBar.statusBarColor(R.color.white)     //状态栏颜色，不写默认透明色
        .statusBarDarkFont(true)           //状态栏字体是深色，不写默认为亮色
        .init();


    }

    /**
     * 隐藏标题与状态栏
     */
    private void requestNoTitle(){
        //隐藏标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    private void initToolbar(){
        mToolbar = findViewById(R.id.toolbar);
        if (null != mToolbar) {
            //设置为actionbar
            setSupportActionBar(mToolbar);
            ActionBar actionBar = getSupportActionBar();
            if (null != actionBar && canBack()) {
                //显示左上角返回按钮
                actionBar.setDisplayHomeAsUpEnabled(true);
            }
            //设置标题
            setTitle("title");
        }

    }

    /**
     * 设置深色的状态栏（黑字）
     */
    public void setDarkStatusBar() {
        // 系统 6.0 以上 状态栏白底黑字的实现方法
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow()
                    .getDecorView()
                    .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

        MIUISetStatusBarLightMode(this.getWindow(), true);
        FlymeSetStatusBarLightMode(this.getWindow(), true);
    }

    public boolean canBack(){
        return false;
    }

    /**
     * 小米白底黑字状态栏适配
     * @param window
     * @param dark
     * @return
     */
    public static boolean MIUISetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            Class clazz = window.getClass();
            try {
                int darkModeFlag = 0;
                Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                darkModeFlag = field.getInt(layoutParams);
                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                if (dark) {
                    extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
                } else {
                    extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
                }
                result = true;
            } catch (Exception e) {

            }
        }
        return result;
    }

    /**
     * 魅族白底黑字状态栏适配
     * @param window
     * @param dark
     * @return
     */
    public static boolean FlymeSetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            try {
                WindowManager.LayoutParams lp = window.getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                window.setAttributes(lp);
                result = true;
            } catch (Exception e) {

            }
        }
        return result;
    }

    public void showLoading(String msg){
        mLoadingDialog =
                new LoadingDialog.Builder(mContext)
                        .setShowMessage(true)
                        .setMessage(msg)
                        .setCancelable(false)
                        .setCancelOutside(false)
                        .create();
        mLoadingDialog.show();
    }

    @Override
    public void showLoading() {
        mLoadingDialog =
                new LoadingDialog.Builder(mContext)
                        .setShowMessage(true)
                        .setMessage("稍等...")
                        .setCancelable(false)
                        .setCancelOutside(false)
                        .create();
        mLoadingDialog.show();
    }

    @Override
    public void hideLoading() {
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void showToast(String msg) {
        Toast.makeText(mContext,msg,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showError(String error) {
        Toast.makeText(mContext,error,Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            //回退
            onBackPressed();
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }

    /**
     * 设置透明状态栏
     * @param flag
     */
    public void setTranslucentStatus(boolean flag){
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        //获取状态栏透明的flag
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (flag) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    public void readyGo(Class<?> cls){
        readyGo(cls,null);
    }

    /**
     * 开启新的activity并且关闭当前的activity
     * @param cls
     */
    public void readyGoThenKill(Class<?> cls){
        readyGoThenKill(cls,null);
    }

    /**
     * 开启新的activity并且关闭当前的activity
     * @param cls
     * @param bundle
     */
    public void readyGoThenKill(Class<?> cls, Bundle bundle){
        readyGo(cls,bundle);
        finish();
    }

    /**
     * 打开一个新的activity并接收返回码
     * @param cls
     * @param requestCode
     */
    public void readyGoForResult(Class<?> cls, int requestCode){
        readyGoForResult(cls,null,requestCode);
    }

    /**
     * 打开一个新的activity并接收返回码
     * @param cls
     * @param bundle
     * @param requestCode
     */
    public void readyGoForResult(Class<?> cls, Bundle bundle, int requestCode){
        Intent intent = new Intent(this,cls);
        if (null != bundle) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent,requestCode);
    }

    public void initAlertDialog(String msg, final AlertDialogCallBack callBack){
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("提示");
        builder.setMessage(msg);
        builder.setPositiveButton("确定",(dialog,which) -> {callBack.clickPositive();});
        builder.setNegativeButton("取消",(dialog,which) -> {callBack.clickNegative();});
        builder.show();
    }

    /**
     * 打开Activity
     * @param cls
     * @param bundle
     */
    public void readyGo(Class<?> cls, Bundle bundle){
        Intent intent = new Intent(this,cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    @Override
    public Context getContext() {
        return mContext;
    }

    public abstract int provideContentViewId();
    public abstract Bundle getBundleExtras(Bundle bundle);

    public interface AlertDialogCallBack{
        void clickPositive();
        void clickNegative();
    }


    protected void initView(){

    }
}
